package sd_services

import (
	"xiehui-service/app/models/sd_models"
	"xiehui-service/global"
)

type carService struct {
}

var CarService = new(carService)

// 获取所有车辆信息
func (carService *carService) GetCars(pageNum, pageSize int) (cars []sd_models.Car, totalPages, totalRecords int64, err error) {

	if pageNum <= 0 {
		pageNum = 1
	}
	if pageSize <= 0 {
		pageSize = 20
	}

	offset := (pageNum - 1) * pageSize
	err = global.App.MSDB.Order("ID DESC").Limit(pageSize).Offset(offset).Find(&cars).Error
	if err != nil {
		return nil, 0, 0, err
	}

	// 获取总记录数
	err = global.App.MSDB.Model(&sd_models.Car{}).Count(&totalRecords).Error
	if err != nil {
		return nil, 0, 0, err
	}

	// 计算总页数
	totalPages = (totalRecords + int64(pageSize) - 1) / int64(pageSize)

	return cars, totalPages, totalRecords, nil
}

// 生成中联的车记录
func (carService *carService) BatSaveCar(car sd_models.Car) (err error) {
	err = global.App.MSDB.Create(&car).Error
	if err != nil {
		return err
	}
	return
}

// 批量生成中联的车记录
func (carService *carService) BatSaveCars(cars []sd_models.Car) (err error) {
	err = global.App.MSDB.CreateInBatches(&cars, 20).Error
	if err != nil {
		return err
	}
	return
}
